const geoip = require('geoip-lite');

module.exports = () => {
  return async function logger(ctx, next) {
    const start = Date.now();

    // Get IP address
    const ip = ctx.request.headers['x-forwarded-for']?.split(',')[0] ||
    ctx.request.headers['x-real-ip'] ||
    ctx.request.ip ||
    ctx.request.ips[0] ||
    ctx.ip;
    console.log(ip)
    // Get geo location
    const geo = geoip.lookup(ip);
    const country = geo ? geo.country : 'Unknown';

    // Wait for the request to finish
    await next();

    // Calculate response time
    const responseTime = Date.now() - start;

    // Save to database
    try {
      if (ctx.url.includes('apiLog') || ctx.url.includes('dashboard')) return
      if (ip === '127.0.0.1') return
      await ctx.service.apiLog.create({
        method: ctx.method,
        url: ctx.url,
        status: ctx.status,
        ip,
        country,
        response_time: responseTime,
      });
    } catch (error) {
      ctx.logger.error('Failed to save API log:', error);
    }
  };
};
